#include "MyStack.h"

// 初始化栈 
void StackInit(MyStack* ps)
{
    assert(ps);
    ps->_a = NULL;
    ps->_capacity = 0;
    ps->_top = 0;
}

// 入栈 
void StackPush(MyStack* ps, STDataType data)
{
    assert(ps);
    if(ps->_top == ps->_capacity)
    {
        int newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
        STDataType* temp = (STDataType*)realloc(ps->_a, sizeof(STDataType) * newcapacity);
        if(temp == NULL)
        {
            perror("realloc error");
            return;
        }
        ps->_capacity = newcapacity;
        ps->_a = temp;
    }
    ps->_a[ps->_top] = data;
    ps->_top++;
}
// 出栈 
void StackPop(MyStack* ps)
{
    assert(ps);
    ps->_top--;
}
// 获取栈顶元素 
STDataType StackTop(MyStack* ps)
{
    assert(ps);
    return ps->_a[ps->_top - 1];
}
// 获取栈中有效元素个数 
int StackSize(MyStack* ps)
{
    assert(ps);
    return ps->_capacity;
}
// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0 
int StackEmpty(MyStack* ps)
{
    assert(ps);
    if(ps->_top = 0)
    {
        return 1;
    }
    return 0;
}
// 销毁栈 
void StackDestroy(MyStack* ps)
{
    assert(ps);
    free(ps->_a);
    ps->_a = NULL;
    ps->_top = -1;
    ps->_capacity = 0;
}